﻿using System.Diagnostics;
using Plugin.BLE;
using Plugin.BLE.Abstractions.Contracts;

namespace MauiBluetooth
{
    /// <summary>
    /// 要获取位置信息 不然扫描不到
    /// </summary>
    public partial class MainPage : ContentPage
    {
        IAdapter adapter1 = null;
        List<IDevice> devices = new List<IDevice>();
        public MainPage()
        {
            InitializeComponent();
            this.Loaded += MainPage_Loaded;
        }

        private void MainPage_Loaded(object? sender, EventArgs e)
        {
            CheckAndRequestLocationPermission();
        }

        public async Task<PermissionStatus> CheckAndRequestLocationPermission()
        {
            PermissionStatus status = await Permissions.CheckStatusAsync<Permissions.LocationWhenInUse>();
            PermissionStatus status2 = await Permissions.CheckStatusAsync<Permissions.Bluetooth>();

            if (status == PermissionStatus.Granted && status2 == PermissionStatus.Granted)
                return status;

            //if (status == PermissionStatus.Denied && DeviceInfo.Platform == DevicePlatform.iOS)
            //{
            //    // 提示用户在设置中打开
            //    // 在iOS上，一旦权限被拒绝，它可能不会再从应用程序中请求
            //    return status;
            //}

            //if (Permissions.ShouldShowRationale<Permissions.LocationWhenInUse>())
            //{
            //    // 询问用户为什么需要权限的额外信息
            //}
            if (status != PermissionStatus.Granted)
            {
                status = await Permissions.RequestAsync<Permissions.LocationWhenInUse>();
            }
            if (status2 != PermissionStatus.Granted)
            {
                status2 = await Permissions.RequestAsync<Permissions.Bluetooth>();
            }

            return status;
        }

        private async void OnCounterClicked(object sender, EventArgs e)
        {
            adapter1 = CrossBluetoothLE.Current.Adapter;
            adapter1.ScanTimeout = 20000;
            adapter1.DeviceAdvertised += Adapter_DeviceAdvertised;
            adapter1.DeviceDiscovered += Adapter1_DeviceDiscovered;
            adapter1.DeviceDisconnected += Adapter1_DeviceDisconnected;
            var ble = CrossBluetoothLE.Current;
            ble.StateChanged += (s, e) =>
            {
                Debug.WriteLine($"The bluetooth state changed to {e.NewState}");
            };
            devices.Clear();
            blueitem.Children.Clear();
            await adapter1.StartScanningForDevicesAsync();
            //await adapter1.StartScanningForDevicesAsync(deviceFilter: sss);
        }

        private void Adapter1_DeviceDisconnected(object? sender, Plugin.BLE.Abstractions.EventArgs.DeviceEventArgs e)
        {
            if (!devices.Contains(e.Device))
            {
                devices.Add(e.Device);
                addytton(e.Device);
            }
        }
        private void addytton(IDevice e)
        {
            MainThread.BeginInvokeOnMainThread(() =>
            {
                Button button = new Button();
                button.Text = e.Name+e.NativeDevice+" "+e.IsConnectable;
                button.BindingContext = e;
                button.Clicked += Button_Clicked1;
                blueitem.Children.Add(button);
            });
        }

        private void Button_Clicked1(object? sender, EventArgs e)
        {
            var btn = sender as Button;
            IDevice dev = btn.BindingContext as IDevice;
            Linke linke = new Linke();
            linke.dev = dev;
            linke.adapter1 = adapter1;
            Navigation.PushAsync(linke);
        }

        private void Adapter1_DeviceDiscovered(object? sender, Plugin.BLE.Abstractions.EventArgs.DeviceEventArgs e)
        {
            if (!devices.Contains(e.Device))
            {
                devices.Add(e.Device);
                addytton(e.Device);
            }
        }


        private void Adapter_DeviceAdvertised(object? sender, Plugin.BLE.Abstractions.EventArgs.DeviceEventArgs e)
        {
            if (!devices.Contains(e.Device))
            {
                devices.Add(e.Device);
                addytton(e.Device);
            }
        }

        private async void Button_Clicked(object sender, EventArgs e)
        {
            await adapter1.StopScanningForDevicesAsync();
        }

        private void Button_Clicked_1(object sender, EventArgs e)
        {
            Button bt = sender as Button;
            bt.Text = adapter1.IsScanning.ToString() + devices.Count.ToString();
        }
    }

}
